package com.yonyou.cyxdms.sysAuth.service.controller;

import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyxdms.sysAuth.service.constants.Constanst;
import com.yonyou.cyxdms.sysAuth.service.service.EmpService;
import com.yonyou.cyxdms.sysAuth.service.service.Login.WechatScanLoginService;
import com.yonyou.cyxdms.sysAuth.service.utill.AesUtil;
import com.yonyou.cyxdms.sysAuth.service.utill.DateUtils;
import com.yonyou.cyxdms.sysAuth.service.vo.weChat.*;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * Title: WechatScanLoginController
 * Description: 微信扫码登录controller
 *
 * @author 李贺
 */

@RestController
@RequestMapping("/wechat")
@Api(value = "微信扫码登录controller", tags = "微信扫码登录controller") //swagger文档
public class WechatScanLoginController {

    private final Logger logger = LoggerFactory.getLogger(WechatScanLoginController.class);

    @Autowired
    private WechatScanLoginService wechatScanLoginService;
    @Autowired
    private EmpService empService;
    @Value("${pcwc.redirectUri}")
    private String redirectUri;

    /**
     * Title: wx_login
     * Description: 重定向到微信扫码登录二维码页面
     * 此处显示要微信要扫描的二维码
     */
    @PostMapping(value = "/w_login")
    public Map<String, String> wLogin() throws ServiceBizException {
        Map<String, String> wechatLoginUrl = wechatScanLoginService.wechatLoginUrl(redirectUri);
        String url = wechatLoginUrl.get("url");
        Map<String, String> map = new HashMap<>();
        map.put("name", "wx");
        map.put("url", url);
        return map;
    }

    /**
     * Title: callback
     * Description: 回调地址处理
     */
    @PostMapping(value = "/callback")
    public Map<String, Object> callback(@RequestBody WechatLoginVO wechatLoginVO) {

        Map<String, Object> map = new HashMap<>();

        ModelAndView model = new ModelAndView();
        String state = wechatLoginVO.getState();
        String code = wechatLoginVO.getCode();
        String strOpenid = "";
        String strAccessToken;
        //日志开始
        logger.error("微信返回的state： " + state);
        logger.error("微信返回的code： " + code);
        //日志结束
        if (code != null && state != null) {
            // 验证state为了用于防止跨站请求伪造攻击
            String decrypt = AesUtil.decrypt(AesUtil.parseHexStr2Byte(state), AesUtil.PW_SECRET_KEY, 16);
            //日志开始
            logger.error("服务端的秘钥： " + Constanst.WX_MD5 + DateUtils.getYYYYMMdd());
            logger.error("前端传回来后解密后秘钥： " + decrypt);
            //日志结束
            if (!(Constanst.WX_MD5 + DateUtils.getYYYYMMdd()).equals(decrypt)) {
                logger.error("900：微信登录解密过程失败！");
                throw new ServiceBizException("微信登录解密过程失败！");
            }
            AccessToken access = wechatScanLoginService.getAccessToken(code);
            //日志开始
            String openid = access.getOpenid();
            if (openid == null) {
                throw new ServiceBizException("微信登录授权失败！");
            }
            logger.error("微信端返回的access： " + access);
            //日志结束

            strOpenid = access.getOpenid();
            //rain 增加获取微信头像
            strAccessToken = access.getAccess_token();
            //日志开始
            logger.error("微信端返回的Openid： " + strOpenid);
            map = this.checkOpenId(strOpenid, wechatLoginVO.getAppId());

            //rain 增加获取微信头像
            WechatInfo wechatInfo = wechatScanLoginService.getWechatInfo(strAccessToken, strOpenid);
            logger.info("微信获取的人员信息" + wechatInfo.toString());
            map.put("wechatInfo", wechatInfo);

        }
        return map;
    }

    @PostMapping(value = "/checkOpenId")
    public Map<String, Object> checkOpenId(@RequestParam("strOpenid") String strOpenid, @RequestParam("appId") String appId) {
        return wechatScanLoginService.checkOpenId(strOpenid, appId);

    }

    @PostMapping(value = "/accountBinding")
    public Map<String, Object> accountBinding(@RequestBody AccountBindingVO accountBindingVO) {

        wechatScanLoginService.accountBinding(accountBindingVO);
        return checkOpenId(accountBindingVO.getOpenid(), accountBindingVO.getAppId());
    }

    @PostMapping(value = "/sendSms")
    public SendVO sendSms(@RequestBody SendVO sendVO) {

        Integer count = empService.getEmpCountByPhone(sendVO.getPhone(), sendVO.getAppId());
        if (count == 0) {
            throw new ServiceBizException("该手机号尚未注册");
        } else if (count > 1) {
            throw new ServiceBizException("该手机号重复");
        }
        wechatScanLoginService.sendSms(sendVO.getPhone(), sendVO.getAppId());
        return sendVO;
    }
}
